// 字段库 sys_field
const db = require('../db')
const { getNowTime, formatTime } = require('../utils/index')

/**
 * 新增字段
 * @param {*} req
 * @param {*} res
 */
exports.addField = (req, res) => {
  // 日期时间格式化
  req.body.create_time = req.body.create_time
    ? formatTime(req.body.create_time)
    : getNowTime()
  // 查询
  const selectSql = `select * from sys_field where is_delete = 0 and (code = ? or name = ?)`
  db.query(selectSql, [req.body.code, req.body.name], (err, results) => {
    if (err) return res.new_send(err)
    // 判断字段名称和字段编码是否存在
    if (results.length >= 2) return res.new_send('字段名称与字段编码已存在')
    if (results.length === 1) {
      const { code, name } = results[0]
      const { code: field_code, name: field_name } = req.body
      if (code === field_code && name === field_name) {
        return res.new_send('字段名称与字段编码已存在')
      }
      if (name === field_name) {
        return res.new_send('字段名称已存在')
      }
      if (code === field_code) {
        return res.new_send('字段编码已存在')
      }
    }
    // 插入数据库
    const insertSql = `insert into sys_field set ?`
    db.query(insertSql, req.body, (err, results) => {
      if (err) return res.new_send(err)
      if (results.affectedRows !== 1) return res.new_send('新增字段失败')
      res.send({
        status: 0,
        message: '新增字段成功',
        data: { insertId: results.insertId }
      })
    })
  })
}

/**
 * 修改字段
 * @param {*} req
 * @param {*} res
 */
exports.updateField = (req, res) => {
  // 日期时间格式化
  req.body.create_time = req.body.create_time
    ? formatTime(req.body.create_time)
    : getNowTime()
  // 查询
  const selectSql = `select * from sys_field where id <> ? and is_delete = 0 and (code = ? or name = ?)`
  db.query(
    selectSql,
    [req.body.id, req.body.code, req.body.name],
    (err, results) => {
      if (err) return res.new_send(err)
      // 判断字段名称和字段编码是否存在
      if (results.length >= 2) return res.new_send('字段名称与字段编码已存在')
      if (results.length === 1) {
        const { code, name } = results[0]
        const { code: field_code, name: field_name } = req.body
        if (code === field_code && name === field_name) {
          return res.new_send('字段名称与字段编码已存在')
        }
        if (name === field_name) {
          return res.new_send('字段名称已存在')
        }
        if (code === field_code) {
          return res.new_send('字段编码已存在')
        }
      }
      //  修改数据库
      const updateSql = `update sys_field set ? where Id = ?`
      db.query(updateSql, [req.body, req.body.id], (err, results) => {
        if (err) return res.new_send(err)
        if (results.affectedRows !== 1) return res.new_send('更新字段失败')
        res.new_send('更新字段成功', 0)
      })
    }
  )
}

/**
 * 删除字段
 * @param {*} req
 * @param {*} res
 */
exports.deleteFieldById = (req, res) => {
  const deleteSql = `update sys_field set is_delete = 1 where id = ?`
  db.query(deleteSql, req.params.id, (err, results) => {
    if (err) return res.new_send(err)
    if (results.affectedRows <= 0) return res.new_send('删除字段失败')
    res.new_send('删除字段成功', 0)
  })
}

/**
 * 获取字段列表
 * @param {*} req
 * @param {*} res
 */
exports.getFieldLsit = (req, res) => {
  // 分页加载
  const page_num = req.query.page_num || 1 //当前的num
  const page_size = req.query.page_size || 10 //当前页的数量
  const name = req.query.name
  const params = [
    (parseInt(page_num) - 1) * parseInt(page_size),
    parseInt(page_size)
  ]
  // 查询
  const selectSql =
    `select a.*, b.username user_name from sys_field as a left join sys_user as b on a.user_id = b.id where a.is_delete = 0` +
    (name ? ` and a.name like '%${name}%'` : '') +
    ` limit ?,?`
  db.query(selectSql, params, (err, results) => {
    if (err) return res.new_send(err)
    if (results.length > 0) {
      results.forEach((item) => {
        item.create_time = formatTime(item.create_time)
      })
    }
    // 列表数据
    let fields = results

    // 查询数据库总数
    const totalSql =
      `select count(*) as total from sys_field where is_delete = 0` +
      (name ? ` and name like '%${name}%'` : '')
    db.query(totalSql, (err, results) => {
      if (err) return res.new_send(err)
      let total = results[0]['total'] // 总数
      res.send({
        status: 0,
        message: '获取字段列表成功',
        page_num,
        page_size,
        total,
        data: fields
      })
    })
  })
}

/**
 * 获取字段信息
 * @param {*} req
 * @param {*} res
 */
exports.getFieldById = (req, res) => {
  const selectSql = `select a.*, b.username user_name from sys_field as a left join sys_user as b on a.user_id = b.id where a.is_delete = 0 and a.id = ?`
  db.query(selectSql, req.params.id, (err, results) => {
    if (err) return res.new_send(err)
    if (results.length > 0) {
      results.forEach((item) => {
        item.create_time = formatTime(item.create_time)
      })
    }
    res.send({
      status: 0,
      message: '获取字段信息成功',
      data: results
    })
  })
}
